﻿using System;
using System.Collections.Generic;
using System.Text;
using Tauren.Business.Entity.Global;
using Tauren.Business.Entity.Model;
using Tauren.Business.Entity.Output;
using Dapper.Contrib.Extensions;
using Dapper;
using System.Linq;
using Tauren.Business.Infrastructure.Globals;

namespace Tauren.Business.DLL.Resouces
{
    public class MenuResourcesBusiness : Base.BaseDLL, IMenuResourcesBusiness
    {
        public MenuResourcesBusiness(IConnectionDLLBase _dLLBase) : base(_dLLBase)
        {
        }

        /// <summary>
        /// 编辑数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool Edit(ModuleResouces data) => this.ResConnection.Update(data);
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="AutoID"></param>
        /// <returns></returns>
        public List<ModuleResouceTable> Get(long AutoID) => this.ResConnection.Query<ModuleResouceTable>($"select m.autoid,m.rescode,m.menucode,m.resoucestype ,mr.`language`,mr.value from moduleresouces m left join moduleresouces_res mr on m.resourceId =mr.resourceId where m.autoid =@AutoId", new ModuleResouces() { AutoId = AutoID }).ToList();

        /// <summary>
        /// 根据模块编码获取指定资源
        /// </summary>
        /// <param name="ModuleCode"></param>
        /// <returns></returns>
        public List<ModuleResouceTable> GetByModuleCode(string ModuleCode) => this.ResConnection.Query<ModuleResouceTable>($"select m.autoid,m.rescode,m.menucode,m.resoucestype ,mr.`language`,mr.value from moduleresouces m left join moduleresouces_res mr on m.resourceId =mr.resourceId where m.menucode =@MenuCode and m.enable =1 and m.isdelete=0", new ModuleResouces() { MenuCode = ModuleCode }).ToList();

        /// <summary>
        /// 根据资源编码获取指定资源
        /// </summary>
        /// <param name="ResourcesCode"></param>
        /// <returns></returns>
        public List<ModuleResouceTable> GetByResourcesCode(string ResourcesCode) => this.ResConnection.Query<ModuleResouceTable>($"select m.autoid,m.rescode,m.menucode,m.resoucestype ,mr.`language`,mr.value from moduleresouces m left join moduleresouces_res mr on m.resourceId =mr.resourceId where m.rescode =@ResCode and m.enable =1  and m.isdelete=0", new ModuleResouces() { ResCode = ResourcesCode }).ToList();

        /// <summary>
        /// 根据ModuleCode和ResCode获取资源
        /// </summary>
        /// <param name="ResourcesCode"></param>
        /// <returns></returns>
        public List<ModuleResouceTable> GetByResCodeAndMoCoed(string ResourcesCode, string ModuleCode, long AutoID)
        {
            string where = "";
            if (AutoID > 0) where = "and m.autoid <> " + AutoID;
            return this.ResConnection.Query<ModuleResouceTable>($"select m.autoid,m.rescode,m.menucode,m.resoucestype ,mr.`language`,mr.value from moduleresouces m inner join moduleresouces_res mr on m.resourceId =mr.resourceId where m.rescode =@ResCode and m.enable =1  and m.isdelete=0 and m.menucode =@MenuCode {where}", new ModuleResouces() { ResCode = ResourcesCode, MenuCode = ModuleCode }).ToList();
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public long Add(ModuleResouces data) => this.ResConnection.Insert(data);

        /// <summary>
        /// 保存多语言数
        /// </summary>
        /// <param name="resoucesRes"></param>
        /// <returns></returns>
        public bool Add(List<ModuleResoucesRes> resoucesRes)
        {
            if (resoucesRes.Any())
            {
                this.ResConnection.Execute($"delete  from moduleresouces_res where resourceId = {resoucesRes.FirstOrDefault().ResourceId};");
                return this.ResConnection.Insert(resoucesRes) >= 0;
            }
            return true;
        }

        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="queryModel"></param>
        /// <param name="Total"></param>
        /// <returns></returns>
        public List<PageModuleResouceTable> Pages(QueryModel queryModel, out long Total)
        {
            Total = 0;
            string where = "";
            if (!string.IsNullOrEmpty(queryModel.KeyWord))
            {
                where += $"  and (m.rescode LIKE '%{queryModel.KeyWord}%' OR mr.value LIKE '%{queryModel.KeyWord}%' )";
            }
            if (string.IsNullOrEmpty(queryModel.SortField))
            {
                queryModel.SortField = "m.AutoId";
                queryModel.IsAsc = true;
            }
            else
            {
                queryModel.SortField = queryModel.SortField.ToLower().Replace("dic_", "").Replace("dic", "").Trim();
            } 
            if (queryModel.paramters.Any())
            {
                queryModel.paramters.ForEach(p =>
                {
                    where += $"  and m.{p.Label} like '%{p.Value}%'  ";
                });
            }
            
            if (queryModel.KeyWords.Any())
            {
                queryModel.KeyWords.ForEach(p =>
                {
                    where += $"  and m.{p.Label}='{p.Value}'";
                });

            }
            string asc = queryModel.IsAsc ? "ASC" : "DESC";
            queryModel.Page = queryModel.Page == 0 ? 1 : queryModel.Page;
            StringBuilder sql = new StringBuilder();
            sql.Append(@$"select count(m.AutoId) as cnt
                        from moduleresouces m
                        left
                        join moduleresouces_res mr on m.resourceId = mr.resourceId and mr.`language` = '{this.Global.Language}'   where isdelete=0    {where} ;");
            sql.Append(@$"select m.autoid, m.rescode, m.menucode, m.resoucestype, mr.`language`, mr.value,
                        m.enable, m.creator, m.creatdate, m.modifier, m.modifdate
                        from moduleresouces m
                        left
                        join moduleresouces_res mr on m.resourceId = mr.resourceId and mr.`language` = '{this.Global.Language}' where isdelete=0    {where}  ORDER BY {queryModel.SortField} {asc} LIMIT {(queryModel.Page - 1) * queryModel.PageSize},{ queryModel.PageSize} ;");
            using (var reader = ResConnection.QueryMultiple(sql.ToString()))
            {
                Total = reader.ReadFirstOrDefault<int>();
                List<PageModuleResouceTable> pageModules = reader.Read<PageModuleResouceTable>().ToList();
                long RowNo = ((queryModel.Page == 0 ? 1 : queryModel.Page) - 1) * queryModel.PageSize + 1;
                pageModules.ForEach(o =>
                {
                    o.RowNo = RowNo;
                    RowNo++;
                });
                return pageModules;
            }
        }

        /// <summary>
        /// 物理删除数据
        /// </summary>
        /// <param name="AutoID"></param>
        /// <returns></returns>
        public bool PhysicallyDeleted(long AutoID) => this.ResConnection.Execute($"delete from moduleresouces where autoid ={AutoID}; delete  from moduleresouces_res where resourceId in(select resourceId from moduleresouces where autoid ={AutoID});") >= 0;

        public ModuleResouces Singe(long AutoID) => this.ResConnection.Get<ModuleResouces>(AutoID);
    }
}
